<template>
  <div class="container">
    <topTitle
      :titleText="filterField.date + titleText"
      :back="true"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon">
      <el-row
        class="toolbar searchInputWidth"
        style="padding-top: 24px !important"
        v-if="!isCounty"
      >
        <el-form :inline="true" :model="filterField" ref="searchConditions">
          <template>
            <el-col :lg="8" :xl="6">
              <el-form-item label="地区" class="row-padding-bottom">
                <el-select
                  v-model="filterField.areaId"
                  filterable
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in areas"
                    :key="index"
                    :label="item.value"
                    :value="item.name"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6"> </el-col>
            <el-col :lg="8" :xl="6"> </el-col>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="getTableList(filterField)"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </template>
        </el-form>
      </el-row>
      <div class="spacing" v-if="!isCounty"></div>
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <div style="margin-bottom: 24px">
          <el-button
            @click="debounceExport(filterField)"
            class="commonBut saveBtn funComBut"
            icon="icon iconfont icondaochu"
          >
            <span class="opetareText">导出</span>
          </el-button>
          <el-button
            type="primary"
            @click="toFillScoreAllocation(filterField)"
            style="width: 76px; position: relative; top: -2px"
            class="commonBtn"
            >评分设置</el-button
          >
        </div>
        <div class="table-wapper">
          <el-table
            ref="table"
            :data="tableList"
            :show-summary="isShowSummary"
            :summary-method="getSummaries"
            v-loading="loading"
            :header-cell-style="{
              background: '#eef1f6',
              color: '#606266',
              'border-color': '#dfe6ec',
            }"
            highlight-current-row
            stripe
            border
          >
            <el-table-column
              v-for="(item, index) in filterFieldingleColList"
              :fixed="true"
              :key="index"
              :prop="item.prop"
              :label="item.label"
              align="center"
              min-width="120"
              :formatter="formatNumber"
            ></el-table-column>
            <el-table-column
              v-for="(item, index) in filterMultiColList"
              :key="index"
              :label="item.label"
              align="center"
            >
              <el-table-column
                v-for="(v, i) in item.children"
                :key="i"
                :label="v.label"
                align="center"
              >
                <el-table-column
                  v-for="(m, n) in v.children"
                  :key="n"
                  :label="m.label"
                  :prop="m.code"
                  align="center"
                  min-width="160"
                >
                  <template slot-scope="scope">
                    <span
                      type="primary"
                      style="margin-right: 0"
                      v-if="m.prop === 'num'"
                    >
                      <span
                        v-if="
                          scope.row[m.code] === null ||
                          scope.row[m.code] === '0'
                        "
                        >0</span
                      >
                      <el-link
                        v-else
                        @click="showDialog(scope.row, v.id)"
                        style="color: #409eff"
                        >{{ scope.row[m.code] }}</el-link
                      >
                    </span>
                    <span v-else>
                      <el-link
                        v-if="scope.row[m.desc]"
                        style="color: #409eff"
                        @click="showExplainDialog(scope.row, m.desc)"
                        >{{
                          (scope.row[m.code] === null ? 0 : scope.row[m.code])
                            | rounding
                        }}</el-link
                      >
                      <span v-else>{{
                        (scope.row[m.code] === null ? 0 : scope.row[m.code])
                          | rounding
                      }}</span>
                    </span>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table-column>
            <!-- 表格数据为空时，页面显示 -->
            <div slot="empty" v-show="isShow">
              <emptyTable emptyText="暂无相关数据"></emptyTable>
            </div>
          </el-table>
        </div>
      </div>
      <div style="text-align: center">
        <el-button
          class="saveScore"
          v-if="actionType === 'edit'"
          @click.native="saveScore('scoreForm')"
          >保存</el-button
        >
      </div>
      <!-- <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" center :close-on-press-escape="false" :close-on-click-modal="false">
                <span>是否确定下载项目明细？</span>
                <span slot="footer" class="dialog-footer">
                    <el-button class="btn cancel" @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" class="btn save" @click="confirmDownload(downloadParama)">确 定</el-button>
                </span>
            </el-dialog> -->
      <el-dialog
        title="说明"
        :visible.sync="explainDialogVisible"
        width="30%"
        center
        :close-on-press-escape="false"
        :close-on-click-modal="false"
      >
        <span>{{ description }}</span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'
export default {
  name: 'AssessmentScoreAllocation',
  data() {
    return {
      titleText: '月度考核详情',
      pickerOptions: {
        disabledDate(time) {
          //如果没有后面的-8.64e7就是不可以选择今天的
          return time.getTime() > Date.now() - 8.64e7
        },
      },
      columnList: [],
      tableList: [],
      downloadParama: {},
      requestUrlL: '',
      filterField: {
        areaId: '',
        date: '',
      },
      areas: [],
      dialogVisible: false,
      explainDialogVisible: false,
      description: '',
      isShow: false,
      loading: false,
      timer: null,
      isCounty: false,
      isShowSummary: true,
    }
  },
  computed: {
    filterFieldingleColList() {
      return this.columnList.filter((v) => {
        return v.children && v.children.length === 0
      })
    },
    filterMultiColList() {
      return this.columnList.filter((v) => {
        return v.children && v.children.length > 0
      })
    },
  },
  filterField: {
    rounding(value) {
      return Math.round(value * 100) / 100
    },
  },
  async created() {
    await this.getAreaList()
    this.filterField.date = this.$route.query.date
    await this.getTableList(this.filterField)
    // 兼容
    if (navigator.userAgent.indexOf('Chrome') > -1) {
      document.querySelector('.el-table__fixed').style.bottom = '7px'
    }
  },
  methods: {
    // 获取地区
    getAreaList() {
      return this.axios({
        method: 'get',
        url: '/api-gov/govexamgrade/areaList',
      })
        .then((response) => {
          if (!response.data.hasError) {
            const results = response.data.result
            this.areas = results
            if (this.areas && this.areas.length === 1) {
              this.isCounty = true
              this.isShowSummary = false
            }
          } else {
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 月度考核详情数据
    getTableList({ areaId = '', date = '' } = {}) {
      this.loading = true
      return this.axios({
        method: 'post',
        url: '/api-gov/govexamgrade/gradeDetails',
        data: {
          areaId,
          date,
        },
      })
        .then((response) => {
          this.loading = false
          if (!response.data.hasError) {
            const results = response.data.result
            this.columnList = results[0]
            this.handleColList(this.columnList)
            if (results[1] && results[1].length > 0) {
              this.isShowSummary = results[1].length === 1 ? false : true
              let dataList = []
              for (let j = 0; j < results[1].length; j++) {
                let keyList = Object.keys(results[1][j])
                let dataObj = {}
                for (let i = 0; i < keyList.length; i++) {
                  if (keyList[i] === 'data') {
                    Object.assign(dataObj, { ...results[1][j][keyList[i]] })
                  } else {
                    Object.assign(dataObj, {
                      [keyList[i]]: results[1][j][keyList[i]],
                    })
                  }
                }
                dataList.push(dataObj)
              }
              this.tableList = this.filterTableList(dataList)
              // this.$nextTick(() => {
              //     this.$refs.table.doLayout()
              // })
            }
            this.isShow = false
            if (this.tableList.length < 1) {
              this.isShow = true
            }
          } else {
            this.isShow = true
            this.$message.error(response.data.errorMsg)
          }
        })
        .catch((error) => {
          this.loading = false
          this.isShow = true
          if (error.response) {
            this.$message.error(error.response.data)
          }
        })
    },
    // 处理表头数据
    handleColList(columnList) {
      if (columnList && columnList.length > 0) {
        for (let i = 0; i < columnList.length; i++) {
          if (columnList[i].children && columnList[i].children.length > 0) {
            for (let j = 0; j < columnList[i].children.length; j++) {
              for (
                let k = 0;
                k < columnList[i].children[j].children.length;
                k++
              ) {
                Object.assign(columnList[i].children[j].children[k], {
                  code:
                    columnList[i].children[j].prop +
                    columnList[i].children[j].children[k].prop,
                  desc: columnList[i].children[j].prop + 'description',
                })
              }
            }
          }
        }
      }
    },
    // 处理表格数据
    filterTableList(tableList) {
      let list = []
      for (let i = 0; i < tableList.length; i++) {
        let keysList = Object.keys(tableList[i])
        let indexObj = {}
        for (let j = 0; j < keysList.length; j++) {
          let preKey = keysList[j]
          if (tableList[i][preKey] instanceof Object) {
            for (let k = 0; k < Object.keys(tableList[i][preKey]).length; k++) {
              let lastKey = Object.keys(tableList[i][preKey])[k]
              Object.assign(indexObj, {
                [preKey + lastKey]: tableList[i][preKey][lastKey],
              })
            }
          } else {
            Object.assign(indexObj, {
              [preKey]: tableList[i][preKey],
            })
          }
        }
        list.push(indexObj)
      }
      return list
    },
    showDialog(row, id) {
      this.downloadParama.gradeId = row.id
      this.downloadParama.configId = id
      // this.dialogVisible = true;
      this.$confirm('是否确定下载项目明细？', '提示', {
        confirmButtonText: '确定',
        type: 'warning',
        showCancelButton: false,
      })
        .then(() => {
          this.confirmDownload(this.downloadParama)
        })
        .catch((action) => {})
    },
    showExplainDialog(row, description) {
      if (row[description]) {
        this.explainDialogVisible = true
        this.description = row[description]
      }
    },
    // 下载项目明细
    confirmDownload({ gradeId = '', configId = '' } = {}) {
      // this.dialogVisible = false;
      window.location.href =
        common.commonApi +
        'api-gov/govexamprojectdetails/export?gradeId=' +
        gradeId +
        '&configId=' +
        configId +
        '&access_token=' +
        localStorage.getItem('access_token')
    },
    // 导出考核详情
    exportDetail({ areaId = '', date = '' } = {}) {
      window.location.href =
        common.commonApi +
        'api-gov/govexamgrade/export?areaId=' +
        areaId +
        '&date=' +
        date +
        '&access_token=' +
        localStorage.getItem('access_token')
      if (this.timer) {
        clearTimeout(this.timer)
      }
    },
    // 跳转填分设置
    toFillScoreAllocation({ areaId = '', date = '' } = {}) {
      if (areaId) {
        this.$router.push({
          path: '/home/enterpriseScore/fillScoreAllocation',
          name: 'FillScoreAllocation',
          query: {
            areaId,
            date,
          },
        })
        this.$store.commit('CHANGE_SLIDER_NAME', {
          oldUrl: '/home/enterpriseScore/assessmentList',
          newUrl: this.$router.currentRoute.fullPath,
        })
      } else {
        this.$message.error('请先选择地区')
      }
    },
    goBack() {
      this.$router.push('/home/enterpriseScore/assessmentList')
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/enterpriseScore/assessmentList',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    // 合计
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (!values.every((value) => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              // 保留位数
              prev = Math.round(prev * 100) / 100
              curr = Math.round(curr * 100) / 100
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          // sums[index] += '元';
          sums[index] = Math.round(sums[index] * 100) / 100
        } else {
          sums[index] = '--'
        }
      })
      return sums
    },
    formatNumber(row, column, cellValue, index) {
      if (!cellValue && cellValue !== 0) {
        return '--'
      } else if (typeof cellValue === 'number') {
        return Math.round(cellValue * 100) / 100
      } else {
        return cellValue
      }
    },
    //防抖
    debounce(fn, delay) {
      // var timer = null; // 维护一个 timer
      var _this = this // 取debounce执行作用域的this
      return function () {
        var args = arguments
        if (_this.timer) {
          clearTimeout(_this.timer)
        }
        _this.timer = setTimeout(function () {
          fn.apply(_this, args) // 用apply指向调用debounce的对象，相当于_this.fn(args);
        }, delay)
      }
    },
    debounceExport(content) {
      this.debounce(this.exportDetail, 500)(content)
    },
    // 节流
    // throttle(fn, time) {
    //     // let canRun = true;
    //     let _this = this;
    //     return function () {
    //         let _arguments = arguments;
    //         if (!_this.canRun) return;
    //         _this.canRun = false;
    //         setTimeout(() => {
    //             fn.apply(_this, _arguments);
    //             _this.canRun = true;
    //         }, time);
    //     }
    // },
    // throttleExport(content) {
    //     this.throttle(this.exportDetail, 1000)(content);
    // },
  },
}
</script>

<style scoped lang="less">
.container {
  .mainCon {
    top: 196px;
    padding: 0;
    padding-bottom: 24px;
    .table-wapper {
      position: relative;
      border-left: 1px solid #ebeef5;
      border-top: 1px solid #ebeef5;
    }
    /deep/ .el-table {
      position: static;
      overflow: auto;
    }
    /deep/ .el-table__body-wrapper,
    /deep/ .el-table__header-wrapper,
    /deep/ .el-table__footer-wrapper {
      overflow: visible;
    }
    /deep/ .el-table::after {
      position: relative !important;
    }
    /deep/ .el-table--border {
      border: none;
    }
    /deep/ .el-table__fixed {
      height: auto !important;
      bottom: 17px;
      // height: calc(100% - 7px) !important;
    }
  }
}
// ::-webkit-scrollbar {
//     height: 17px;
// }
</style>
